﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Read.API.Command.UserCommand;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace B.S.BaseData.Read.API.CommandHandler.UserHandler
{
    public class LoginUserHandler : IRequestHandler<LoginUserCommand, APIResult<User>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<UserRole> urRep;
        private readonly ILogger<LoginUserCommand> logger;
        private readonly IDatabase redisDatabase;

        public LoginUserHandler(
            IBaseRepository<User> userRep,
            IMapper mapper,
            IBaseRepository<UserRole> urRep,
            ILogger<LoginUserCommand> logger,
            IConnectionMultiplexer redis)
        {
            this.userRep = userRep;
            this.mapper = mapper;
            this.urRep = urRep;
            this.logger = logger;
            this.redisDatabase = redis.GetDatabase(); // 通过 IConnectionMultiplexer 获取 IDatabase 实例
        }

        public Task<APIResult<User>> Handle(LoginUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<User> result = new APIResult<User>();

            var user = userRep.GetAll().Where(x => x.Name == request.Name).FirstOrDefault();

            if (user == null)
            {
                result.Code = APIEnum.用户名不存在;
                result.Msg = APIEnum.用户名不存在.ToString();
            }
            else
            {
                var roleId = urRep.GetAll().Where(x => x.UserId == user.UserId).FirstOrDefault()?.RoleId.ToString();
                if (user.Pass != request.Pass)
                {
                    result.Code = APIEnum.用户名和密码不匹配;
                    result.Msg = APIEnum.用户名和密码不匹配.ToString();
                }
                else
                {
                    // 存储用户名和密码到 Redis
                    StoreLoginInfoInRedis(user.Name, user.Pass);

                    result.Code = APIEnum.登陆成功;
                    result.Msg = CreateTokenString(user.UserId.ToString(), roleId);
                    result.Data = user;
                    logger.LogInformation(user.Name + " 登陆成功！");
                }
            }

            return Task.FromResult(result);
        }

        private void StoreLoginInfoInRedis(string username, string password)
        {
            string hashedPassword = HashPassword(password);
        //    redisDatabase.StringSet(username, hashedPassword);
            Console.WriteLine($"用户名 {username} 和密码已存储到 Redis（字符串类型）。");
        }

        private string HashPassword(string password)
        {
            using (var sha256 = System.Security.Cryptography.SHA256.Create())
            {
                var bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
                return Convert.ToBase64String(bytes);
            }
        }

        private string CreateTokenString(string uid, string rid)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, uid),
                new Claim(ClaimTypes.Role, rid)
            };

            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            var signingKey = new SymmetricSecurityKey(secretByte);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(1),
                signingCredentials: signingCredentials
            );


            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}